# Import the base class and a ploting method
import readchn
import numpy
import pylab
import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm
import csv
import os
import datetime

with open('radonnew.csv','r') as f:
   rnlog = csv.reader(f,delimiter='\t')

data_dir = '/Users/bung/POSTWORK/RnCart/data/'
run_data = {}
num_spec = 0
num_chan = 0
for i in os.listdir(data_dir):
   #print 'WIPP Data Dir: %s'%i
   try:
      run_date = datetime.datetime.strptime(i,'%y%m%dE5')
   except:
      continue
   if run_date > datetime.datetime(2011,1,1,0,0,1):
      run_data[i] = readchn.esc_run(data_dir+i,{'verbose':0})
      if run_data[i].header[0]['livetime'] < 3600*24*5:
         print 'Not enough data to care for %s'%i
         del run_data[i]
      #num_spec += len(run_data[i].data)
      
days = sorted(run_data.keys())
#days.sort()
ys,ye = [],[] #where each run starts and stops
line = numpy.ones((1,run_data[days[0]].header[0]['nchan']))*1000
ys.append(0)
all_data = run_data[days[0]].data
ye.append(len(all_data))
for d in days[1:]:
   print d
   if len(run_data[d].data)==0: continue
   ys.append(len(all_data))
   all_data = numpy.concatenate((all_data,line,run_data[d].data))
   ye.append(len(all_data))


fig = plt.figure(figsize=(20,8), dpi=200)
ax1 = fig.add_subplot(111)
cax1 = plt.imshow(all_data.T, interpolation='none', aspect='auto', norm=LogNorm(vmin=1,vmax=all_data.max()))
pylab.colorbar()
ax1.set_xticks(ys)
ax1.set_xticklabels(days,fontsize=8,rotation=65)
ax1.set_ylabel('Channel number')
ax1.set_xlabel('Date (then each spectrum in order)') 
ax1.set_title('Accumulated Counts for Many Runs')
plt.savefig("Wipp_data_diode.pdf")

ys=[]
ye=[]
line = numpy.ones((1,run_data[days[0]].header[0]['nchan']))*10
ys.append(0)
all_data = run_data[days[0]].idata
ye.append(len(all_data))
for d in days[1:]:
   print d
   if len(run_data[d].idata)==0: continue
   ys.append(len(all_data))
   all_data = numpy.concatenate((all_data,line,run_data[d].idata))
   ye.append(len(all_data))


fig2 = plt.figure(figsize=(20,8), dpi=200)
ax2 = fig2.add_subplot(111)
for i,d in enumerate(all_data):
   for j in range(len(d)):
      if all_data[i][j] >30: all_data[i][j]=30
#for i,d in enumerate(all_data):
#   for j in range(len(d)):
#      if all_data[i][j] <0: all_data[i][j]=0
cax2 = plt.imshow(all_data.T)
pylab.colorbar()
ax2.set_xticks(ys)
ax2.set_xticklabels(days,fontsize=8,rotation=65)
ax2.set_ylabel('Channel number')
ax2.set_xlabel('Date (then each spectrum in order)') 
ax2.set_title('Accumulated Counts for Many Runs')
plt.savefig("Wipp_data_diode_lin.pdf")

